package com.zhaowudi.wj.controller;

import com.zhaowudi.wj.pojo.Book;
import com.zhaowudi.wj.result.Result;
import com.zhaowudi.wj.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
public class LibraryController {
    private Logger logger = LoggerFactory.getLogger(LibraryController.class);
    @Autowired
    BookService bookService;
//
//    @Autowired
//    Result result;

    @GetMapping(value = "/api/books")//, produces = MediaType.APPLICATION_XML_VALUE
    public Result list() throws Exception {
        Result result = new Result();


        List<Book> Booklist = new ArrayList<>();
        Booklist = bookService.Alllist();
        if (Booklist.size() > 0) {
            result.code = 200;
            result.data = Booklist;
            logger.error("成功");
        } else {
            result.code = 400;
            result.data = "获取书籍错误";
            logger.error(result.data.toString());
        }

        return result;
    }

    @PostMapping("/api/book/add")
    public Result add(@RequestBody List<Book> bookList) throws Exception {
        Result result = new Result();
        try {
            for (Book book : bookList) {
                bookService.add(book);
            }
        } catch (Exception e) {
            result.code = 500;
            result.data = "新增失败";
        } finally {
            return result;
        }
    }

    @PostMapping("/api/book/addEX")
    public void addEX(@RequestBody List<Book> bookList) throws Exception {
        bookService.addEX(bookList);
    }

    @PostMapping("/api/delete")
    public void delete(@RequestBody Book book) throws Exception {
        bookService.deleteById(book.getId());
    }


    @GetMapping("/api/categories/{cid}/books")
    public List<Book> listByCategory(@PathVariable("cid") int cid) throws Exception {
        if (0 != cid) {
            return bookService.listByCategory(cid);
        } else {
            return (List<Book>) list();
        }
    }
}

